package com.hsh.server.util.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceTask {
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    public static final String ONLINE_OPERRATOR = RedisConstants.USER_SIGN_KEY;

    /**
     * redis序列化存储
     *
     * @param redisTemplate
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public void setToken(String key, String token) {
        ValueOperations<String, String> value = redisTemplate.opsForValue();
        value.set(ONLINE_OPERRATOR + key, token);
    }

    public void setTokenWithTime(String key, String token, long number, TimeUnit timeUnit) {
        ValueOperations<String, String> value = redisTemplate.opsForValue();
        value.set(ONLINE_OPERRATOR + key, token, number, timeUnit);
    }

    public void freshTime(String key) {
        redisTemplate.expire(key, expireTime* MILLIS_MINUTE, TimeUnit.SECONDS);
    }

    public String getToken(String key) {
        return redisTemplate.boundValueOps(ONLINE_OPERRATOR +key).get();

    }
}
